package cc.marcio.systems.seven.main;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;

import org.apache.log4j.Logger;

import cc.marcio.systems.seven.dao.DaoFactory;
import cc.marcio.systems.seven.model.User;
import cc.marcio.systems.seven.process.AtualizaRoundProcess;
import cc.marcio.systems.seven.process.BaseProcess;
import cc.marcio.systems.seven.process.CreateEventProcess;
import cc.marcio.systems.seven.process.GmailProcess;
import cc.marcio.systems.seven.process.TrafegoProcess;
import cc.marcio.systems.seven.util.MessageUtil;


public class ExecutionProcess extends Thread {

	private Logger logger = Logger.getLogger(this.getClass());

	private List<BaseProcess> process;
	
	private Date mark;
	
	private Integer minutesToLoop;
	
	@Override
	public synchronized void start() {
		this.logger.info("Starting all process");
		ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(MessageUtil.getInteger("process.pool.thread.size"));
		Calendar now = Calendar.getInstance();
		
		if( this.minutesToLoop.equals(0) ) {
			new AtualizaRoundProcess().process();
			for( BaseProcess p : this.process ) {
				stpe.execute(p);
			}
			new CreateEventProcess().process();
			stpe.shutdown();
		} else {
			
			while( true ) {
				if( this.mark == null || now.getTimeInMillis() < new Date().getTime() ) {
					this.mark = new Date();
					now.setTime(this.mark);
					now.add(Calendar.MINUTE, this.minutesToLoop);
					
					// Atualizando Round
					new AtualizaRoundProcess().process();
					
					for( BaseProcess p : this.process ) {
						stpe.execute(p);
					}
					
					new CreateEventProcess().process();
				}
			}
		}
		stpe.shutdown();
	}

	public ExecutionProcess(Integer minutesToLoop) {
		this.setName("ExecutionProcess");
		this.process = new ArrayList<BaseProcess>();
		this.mark = null;
		this.minutesToLoop = minutesToLoop;
		
		List<User> users = DaoFactory.getUserDao().findUsersWithPlanetsActive();
		for( User user : users ) {
			this.addProcess(new GmailProcess(user));
			this.addProcess(new TrafegoProcess(user));
		}
		this.start();
	}
	
	public void addProcess(BaseProcess process) {
		this.process.add(process);
	}	
	
	public static void main(String [] args) {
		new ExecutionProcess(MessageUtil.getInteger("process.time.loop.in.minutes"));		
	}
}